﻿using System;
using System.Collections.Generic;

using PuSuoPai;

namespace DTFight
{
	public class GameMgr
	{
		static readonly public GameMgr Instance = new GameMgr();


		public const int ROOM_COUNT = 100;
		public const int PLAYER_PER_ROOM = 100;

		GameData[] Rooms = new GameData[ROOM_COUNT];

		Dictionary<string, PlayerData> PlayerList = new Dictionary<string, PlayerData> ();

		public void Init()
		{
			// init cards
			CardData.InitCardPool();

			// init rooms
			for (int i=0; i<Rooms.Length; ++i) {
				Rooms[i] = new GameData ();
				Rooms [i].Init ();
			}
		}

		public void Update()
		{
			foreach (var room in Rooms) {
				if (room.CurStateInfo.StateFlag == (UInt32)GameData.STATE_FLAG.MAX) {
					if (room.PlayerCount == 0)
						continue;
					else
						room.Start ();
				}

				room.Update ();

				if (room.CurStateInfo.StateFlag == (UInt32)GameData.STATE_FLAG.MAX) {
					SendRoomBroadcast (room);
				}
			}
		}

		public void Destroy()
		{
		}

		public PlayerData GetPlayer(string playerId)
		{
			if (PlayerList.ContainsKey (playerId))
				return PlayerList [playerId];

			return null;
		}

		public GameData GetRoom(string playerId)
		{
			PlayerData player = GetPlayer (playerId);
			if (player == null)
				return null;

			return GetRoom(player.CurRoomId);
		}

		public GameData GetRoom(int idx)
		{
			if (idx <= 0 || idx-1 >= Rooms.Length)
				return null;

			return Rooms [idx-1];
		}

		public bool EnterRoom(int roomId, PlayerData player)
		{
			if (player == null)
				return false;

			if (roomId <= 0 || roomId > ROOM_COUNT)
				return false;

			GetRoom (roomId).PlayerEnter (player);
			player.WinPointsInRoom = 0;
			player.CurRoomId = roomId;

			PlayerList [player.PlayerId] = player;

			return true;
		}

		public void ExitRoom(string playerId)
		{
			PlayerData player = null;
			if (!PlayerList.TryGetValue (playerId, out player))
				return;

			if (player == null)
				return;

			if (player.CurRoomId <= 0 || player.CurRoomId > ROOM_COUNT)
				return;
				
			GameData room = GetRoom (player.CurRoomId);
			if (room != null && room.PlayerLeave (player.PlayerId)) {
				player.CurRoomId = -1;
			}

		}

		void SendRoomBroadcast(GameData room)
		{
//			switch ((GameData.STATE_FLAG)room.CurStateInfo.StateFlag) {
//			case GameData.STATE_FLAG.SELECT_GROUP:
//				//RoomMsg.Instance ().SendGameStart (room);
//				break;
//			case GameData.STATE_FLAG.OPEN_NONE:
//			case GameData.STATE_FLAG.OPEN_CARD_1:
//			case GameData.STATE_FLAG.OPEN_CARD_2:
//			case GameData.STATE_FLAG.OPEN_CARD_3:
//			case GameData.STATE_FLAG.OPEN_CARD_4:
//				//RoomMsg.Instance ().SendGameShowCard (room);
//				break;
//			case GameData.STATE_FLAG.SHOW_BET_RESULT:
//				//RoomMsg.Instance ().SendGameOver (room, room.ResultList[room.ResultList.Count-1]);
//				break;
//			}
		}
	}
}

